﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;

namespace TSharp.Core.AppBox.Handlers
{
    public class ThreadPoolHandlerFactory : IHttpHandlerFactory, IRequiresSessionState
    {
        public static List<Type> types = typeof(ThreadPoolHandlerFactory).Assembly.GetTypes().Where(x => x.Namespace.StartsWith("TSharp.Core.AppBox.Handlers")).ToList();
        static Type c = typeof(BaseHttpHandler);
        public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
            var t = context.Request.Url.Segments;
            if (t.Length > 0)
            {
                var handlerName = t[t.Length - 1];
                var type = types.Find(x => handlerName.Equals(x.Name + ".axd", StringComparison.OrdinalIgnoreCase));
                if (type == null)
                    type = types.Find(x => handlerName.Contains(x.Name));



                if (type != c && type != null && c.IsAssignableFrom(type) && !type.IsAbstract && !type.IsInterface)
                {
                    return Activator.CreateInstance(type, context, requestType, url, pathTranslated) as IHttpHandler;
                }
            }

            return new NullHttpHandler(context, requestType, url, pathTranslated);
        }

        public void ReleaseHandler(IHttpHandler handler)
        {
            var dispose = handler as IDisposable;
            if (dispose != null)
                dispose.Dispose();
        }
    }
}